import React, { useEffect, useState, useRef } from 'react';
import './QuestionTable.css';

interface Question {
  id: number;
  title: string;
  content: string;
  type: string;
  options?: string;
  answer: string;
  createdTime: string;
  updatedTime: string;
  creator?: string;
}

interface QuestionTableProps {
  onEdit: (q: Question) => void;
  onDelete: (ids: number[]) => void;
  refreshFlag?: boolean;
}

const PAGE_SIZE_OPTIONS = [10, 20, 50];
const TYPE_TABS = [
  { label: '全部', value: '' },
  { label: '单选题', value: '单选题' },
  { label: '多选题', value: '多选题' },
  { label: '编程题', value: '编程题' },
];

const QuestionTable: React.FC<QuestionTableProps> = ({ onEdit, onDelete, refreshFlag }) => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [type, setType] = useState(() => localStorage.getItem('questionTableType') || '');
  const [keyword, setKeyword] = useState(() => localStorage.getItem('questionTableKeyword') || '');
  const [page, setPage] = useState(() => Number(localStorage.getItem('questionTablePage')) || 1);
  const [pageSize, setPageSize] = useState(() => Number(localStorage.getItem('questionTablePageSize')) || 10);
  const [total, setTotal] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const [showDropdown, setShowDropdown] = useState(false);
  const [pageInput, setPageInput] = useState(() => localStorage.getItem('questionTablePage') || '1');

  // 从 localStorage 恢复状态并获取数据
  useEffect(() => {
    const params = new URLSearchParams({
      type,
      keyword,
      pagenum: String(page),
      pagesize: String(pageSize),
    });

    fetch(`/api/questions?${params}`)
      .then(res => res.json())
      .then(data => {
        if (data.list && Array.isArray(data.list)) {
          setQuestions(data.list);
          setTotal(data.total || 0);
        } else {
          setQuestions([]);
          setTotal(0);
        }
      });

    // 恢复搜索框的值
    if (inputRef.current && keyword) {
      inputRef.current.value = keyword;
    }
  }, []);

  // 保存状态到 localStorage
  useEffect(() => {
    localStorage.setItem('questionTableType', type);
    localStorage.setItem('questionTableKeyword', keyword);
    localStorage.setItem('questionTablePage', String(page));
    localStorage.setItem('questionTablePageSize', String(pageSize));
  }, [type, keyword, page, pageSize]);

  // 监听 refreshFlag 变化
  useEffect(() => {
    if (refreshFlag !== undefined) {
      const params = new URLSearchParams({
        type,
        keyword,
        pagenum: String(page),
        pagesize: String(pageSize),
      });

      fetch(`/api/questions?${params}`)
        .then(res => res.json())
        .then(data => {
          if (data.list && Array.isArray(data.list)) {
            setQuestions(data.list);
            setTotal(data.total || 0);
          } else {
            setQuestions([]);
            setTotal(0);
          }
        });
      setSelectedIds([]);
    }
  }, [refreshFlag]);

  const handleSelect = (id: number, checked: boolean) => {
    setSelectedIds(checked ? [...selectedIds, id] : selectedIds.filter(i => i !== id));
  };

  const handleSelectAll = (checked: boolean) => {
    setSelectedIds(checked ? questions.map(q => q.id) : []);
  };

  const handleTab = (val: string) => {
    setType(val);
    setPage(1);
    setPageInput('1');
    // 获取数据
    const params = new URLSearchParams({
      type: val,
      keyword,
      pagenum: '1',
      pagesize: String(pageSize),
    });
    fetch(`/api/questions?${params}`)
      .then(res => res.json())
      .then(data => {
        if (data.list && Array.isArray(data.list)) {
          setQuestions(data.list);
          setTotal(data.total || 0);
        }
      });
  };

  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement> | React.MouseEvent) => {
    if ((e as React.KeyboardEvent).key === 'Enter' || (e as React.MouseEvent).type === 'click') {
      const newKeyword = inputRef.current?.value || '';
      setKeyword(newKeyword);
      setPage(1);
      setPageInput('1');
      // 获取数据
      const params = new URLSearchParams({
        type,
        keyword: newKeyword,
        pagenum: '1',
        pagesize: String(pageSize),
      });
      fetch(`/api/questions?${params}`)
        .then(res => res.json())
        .then(data => {
          if (data.list && Array.isArray(data.list)) {
            setQuestions(data.list);
            setTotal(data.total || 0);
          }
        });
    }
  };

  // 关闭下拉菜单的全局点击事件
  React.useEffect(() => {
    if (!showDropdown) return;
    const handleClick = (e: MouseEvent) => {
      const dropdown = document.querySelector('.dropdown-menu');
      if (dropdown && !dropdown.contains(e.target as Node)) {
        setShowDropdown(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showDropdown]);

  const handleDeleteConfirm = (ids: number[]) => {
    if (confirm('确认删除选中的题目吗？')) {
      onDelete(ids);
    } else {
      if (ids.length > 1) {
        setSelectedIds([]);
      }
    }
  };

  const handlePageClick = (newPage: number) => {
    if (newPage < 1 || newPage > Math.ceil(total / pageSize)) return;
    setPage(newPage);
    setPageInput(String(newPage));
    // 获取数据
    const params = new URLSearchParams({
      type,
      keyword,
      pagenum: String(newPage),
      pagesize: String(pageSize),
    });
    fetch(`/api/questions?${params}`)
      .then(res => res.json())
      .then(data => {
        if (data.list && Array.isArray(data.list)) {
          setQuestions(data.list);
          setTotal(data.total || 0);
        }
      });
  };

  const handlePageJump = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const newPage = parseInt(pageInput) || 1;
      const maxPage = Math.ceil(total / pageSize);
      const validPage = Math.max(1, Math.min(newPage, maxPage));
      handlePageClick(validPage);
    }
  };

  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newPageSize = Number(e.target.value);
    setPageSize(newPageSize);
    setPage(1);
    setPageInput('1');
    // 获取数据
    const params = new URLSearchParams({
      type,
      keyword,
      pagenum: '1',
      pagesize: String(newPageSize),
    });
    fetch(`/api/questions?${params}`)
      .then(res => res.json())
      .then(data => {
        if (data.list && Array.isArray(data.list)) {
          setQuestions(data.list);
          setTotal(data.total || 0);
        }
      });
  };

  // 修改分页按钮渲染逻辑
  const renderPagination = () => {
    const pageCount = Math.max(1, Math.ceil(total / pageSize));
    const pages: (number | string)[] = [];

    if (pageCount <= 5) {
      // 如果总页数小于等于5，显示所有页码
      for (let i = 1; i <= pageCount; i++) {
        pages.push(i);
      }
    } else {
      // 始终显示第一页
      pages.push(1);

      // 当前页靠近开始
      if (page <= 3) {
        pages.push(2, 3, '...', pageCount);
      }
      // 当前页靠近结束
      else if (page >= pageCount - 2) {
        pages.push('...', pageCount - 2, pageCount - 1, pageCount);
      }
      // 当前页在中间
      else {
        pages.push('...', page - 1, page, page + 1, '...', pageCount);
      }
    }

    return pages.map((p, idx) =>
      typeof p === 'number' ? (
        <button
          key={p}
          className={page === p ? 'active' : ''}
          onClick={() => handlePageClick(p)}
        >
          {p}
        </button>
      ) : (
        <span key={idx} style={{ padding: '0 4px' }}>...</span>
      )
    );
  };

  return (
    <div className="question-table-wrapper">
      {/* 工具栏：类型和搜索同一行，按钮单独一行居右 */}
      <div className="question-table-toolbar-row" style={{ display: 'flex', alignItems: 'center', marginBottom: 32 }}>
        <div className="type-tabs" style={{ display: 'flex', alignItems: 'center' }}>
          <span style={{ marginRight: 8, fontSize: 16 }}>题型：</span>
          {TYPE_TABS.map(tab => (
            <button
              key={tab.value}
              className={type === tab.value ? 'active' : ''}
              onClick={() => handleTab(tab.value)}
              style={{ marginRight: 8, fontSize: 16, padding: '6px 20px' }}
            >{tab.label}</button>
          ))}
        </div>
        <div className="search-bar" style={{ marginLeft: 32, flex: 1, display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: '#bbb', fontSize: 16 }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="7" cy="7" r="5.5" stroke="#bbb" strokeWidth="1.5"/>
              <line x1="11.2426" y1="11.5355" x2="15" y2="15.2929" stroke="#bbb" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          </span>
          <input
            ref={inputRef}
            placeholder="请输入试题名称"
            onKeyDown={handleSearch}
            className="search-input"
            style={{ width: 500, height: 30, fontSize: 16, paddingLeft: 32 }}
          />
        </div>
      </div>
      <div className="question-table-toolbar-row" style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12, gap: 8 }}>
        <button
          className="add-btn"
          onClick={() => setShowDropdown((v) => !v)}
          style={{ position: 'relative', marginRight: 8, minWidth: 80, height: 35, fontSize: 15, fontWeight: 400 }}
        >
          + 出题 <span style={{ fontSize: 12 }}>▼</span>
          {showDropdown && (
            <div className="dropdown-menu">
              <div onClick={() => { setShowDropdown(false); window.dispatchEvent(new CustomEvent('manual-create')); }}>自主出题</div>
              <div onClick={() => { setShowDropdown(false); window.dispatchEvent(new CustomEvent('ai-create')); }}>AI出题</div>
            </div>
          )}
        </button>
        <button
          className="batch-delete-btn"
          onClick={() => handleDeleteConfirm(selectedIds)}
          disabled={selectedIds.length === 0}
          style={{ minWidth: 80, height: 35, fontSize: 15, fontWeight: 400 }}
        >批量删除</button>
      </div>
      <table className="question-table">
        <thead>
          <tr>
            <th><input type="checkbox" checked={selectedIds.length === questions.length && questions.length > 0} onChange={e => handleSelectAll(e.target.checked)} /></th>
            <th>题目</th>
            <th>题型</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {questions.map(q => (
            <tr key={q.id}>
              <td><input type="checkbox" checked={selectedIds.includes(q.id)} onChange={e => handleSelect(q.id, e.target.checked)} /></td>
              <td style={{color:'#1677ff', cursor:'default'}}>{q.title}</td>
              <td>{q.type}</td>
              <td>
                <button className="edit-btn" onClick={() => onEdit(q)}>编辑</button>
                <button className="delete-btn" onClick={() => handleDeleteConfirm([q.id])}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="question-table-pagination" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 8, marginTop: 20 }}>
        <span>共 {total} 条</span>
        <button disabled={page === 1} onClick={() => handlePageClick(page - 1)}>&lt;</button>
        {renderPagination()}
        <button disabled={page === Math.ceil(total / pageSize) || Math.ceil(total / pageSize) === 0} onClick={() => handlePageClick(page + 1)}>&gt;</button>
        <select value={pageSize} onChange={handlePageSizeChange}>
          {PAGE_SIZE_OPTIONS.map(size => <option key={size} value={size}>{size} 条/页</option>)}
        </select>
        <span>跳至</span>
        <input
          type="text"
          value={pageInput}
          onChange={(e) => setPageInput(e.target.value.replace(/[^0-9]/g, ''))}
          onKeyDown={handlePageJump}
          style={{ width: 50, margin: '0 4px' }}
        />
        <span>页</span>
      </div>
    </div>
  );
};

export default QuestionTable;